package com.agentframework.examples.jinhua;

import com.agentframework.core.agent.AbstractAgent;
import com.agentframework.core.agent.Agent;
import com.agentframework.core.annotation.Action;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;

import java.util.List;
import java.util.Set;

import static com.agentframework.core.agent.Agent.ACTION;

/**
 * 处理玩家比牌动作
 * @author wangjun
 */
@Action(name = "compare")
public class CompareAction extends JinhuaDealerAction {
    
    public CompareAction(JinhuaTool jinhuaTool) {
        super("compare", jinhuaTool);
    }
    
    @Override
    protected String getFormatInstruction() {
        return """
            你需要处理玩家的比牌请求，请必须且只能返回如下JSON格式：
            {
                "playerId": "发起比牌的玩家ID",
                "targetId": "被比牌的玩家ID",
                "winnerId": "获胜的玩家ID",
                "message": "比牌结果的消息",
                "nextPlayerId": "下一个玩家"
            }
            
            例如：
            {
                "playerId": "玩家ID（例如：e9fc1d4d）",
                "targetId": "玩家ID（例如：e9fc1d4d）",
                "winnerId": "玩家ID（例如：e9fc1d4d）",
                "message": "玩家1与玩家2比牌，玩家1获胜",
                "nextPlayerId": "下一个玩家ID（例如：e9fc2db4d）"
            }
            
            请使用compare进行玩家比牌，参数为发起比牌的玩家ID和被比牌的玩家ID
            """;
    }

    @Override
    protected void doHandleResponseMessage(Message message, Object response) {
        CompareResp compareResp = (CompareResp) response;
        String playerId = compareResp.playerId();
        String targetId = compareResp.targetId();
        String winnerId = compareResp.winnerId();
        String messageContent = compareResp.message();
        String nextPlayerId = compareResp.nextPlayerId();

        // 通知玩家比牌结果
//        Message compareMessage = new UserMessage(messageContent);
//        compareMessage.getMetadata().put(Agent.MSG_FROM, agent.getAgentId());
//        compareMessage.getMetadata().put(Agent.SEND_TO, Set.of(playerId, targetId));
//        publishMessage(compareMessage);

        // 广播比牌信息给所有玩家
        Message broadcastMessage = new UserMessage(String.format("玩家%s与%s比牌，%s获胜", playerId, targetId, winnerId));
        broadcastMessage.getMetadata().put(Agent.SEND_TO, getPlayerIds());
        broadcastMessage.getMetadata().put(Agent.VIEW_TO, getPlayerIds());
        publishMessage(broadcastMessage);

        logger.debug("玩家{}与{}比牌，{}获胜", playerId, targetId, winnerId);

        // 比完牌之后，检查是否还剩下一个玩家，如果是剩下一个玩家，就进入下一轮，如果轮数已经达到最大数，那么就结束游戏
        if (isRoundOver()) {
            logger.debug(">>>CompareAction doHandleResponseMessage 只剩下一名玩家存活，本轮结束，开启新的一轮");
            getJinhuaGameState().saveRoundSnapshot();
            // 通知荷官开启新的一轮
            if (!getJinhuaGameState().nextRound()) {
                logger.debug("游戏已经结束");
                getJinhuaGameState().exportGameReport();
            } else {
                getJinhuaGameState().exportGameReport();
                JinhuaGameState jinhuaGameState = getJinhuaGameState();
                jinhuaGameState.getDealerAgent().clear();
                List<Agent> playerAgents = jinhuaGameState.getPlayerAgents();
                for (Agent playerAgent : playerAgents) {
                    AbstractAgent agent = (AbstractAgent) playerAgent;
                    agent.clear();
                }
                logger.debug("是否已经消除消息:{}" ,jinhuaGameState.getDealerAgent().getHistoryMessages());
                logger.debug("============清除了消息，开启下新一轮了=================");
                getJinhuaGameState().getDealerAgent().getHistoryMessages();
                Message newRoundMsg = new UserMessage("开始新一轮游戏,重新发牌等等");
                newRoundMsg.getMetadata().put(Agent.SEND_TO, Set.of(getDealerAgentId()));
                newRoundMsg.getMetadata().put(ACTION, "start_new_round");
                publishMessage(newRoundMsg);
            }
        } else {
            // 通知下一个玩家行动
            Message nextMessage = new UserMessage(messageContent);
            nextMessage.getMetadata().put(Agent.SEND_TO, Set.of(nextPlayerId));
            publishMessage(nextMessage);
        }
    }

    @Override
    protected Class<?> getResponseType() {
        return CompareResp.class;
    }

    record CompareResp(String playerId, String targetId, String winnerId, String message, String nextPlayerId) {

    }

} 